import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions, ProFormCheckbox,
    ProFormText,
    ProFormTextArea,
    ProTable,
    ProFormDateRangePicker, ProFormDigit, ProFormUploadButton, ProFormSelect,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Tag, Badge, Space, Statistic} from 'antd';
import React, {useRef, useState} from 'react';
import type {HostComputerListItem} from './data';
import {hostComputerDelete, hostComputerList} from './service';
import {Link, HistoryRouterProps} from "react-router-dom";
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {skuSelectList} from "@/pages/power/sku/sku-list/service";
import {useAccess, Access} from 'umi';
import {HostComputerOrderStatusEnum, NetworkConnTypeEnum} from "@/pages/data.enum";
import AddNetworkModalForm from "@/pages/power/network/add";
import ConfigNetworkModalForm from "@/pages/power/host-computer/edit/network";
import {organizationSelectList} from "@/pages/organization/org-list/service";

const {confirm} = Modal;

const handleRemove = async (selectedRows: HostComputerListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await hostComputerDelete({
            hostComputerIds: selectedRows.map((row) => row.hostComputerId),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const HostComputerList: React.FC = () => {
    /** 分布更新窗口的弹窗 */
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<HostComputerListItem>();
    const [selectedRowsState, setSelectedRows] = useState<HostComputerListItem[]>([]);
    const [configNetworkModelVisible, handleConfigNetworkModelVisible] = useState<boolean>(false);
    const access = useAccess();
    const rowSelection = access.isSystem
        ? {
            onChange: (_: any, selectedRows: React.SetStateAction<HostComputerListItem[]>) => {
                setSelectedRows(selectedRows);
            },
        }
        : false;
    /** 国际化配置 */
    const columns: ProColumns<HostComputerListItem>[] = [
        {
            title: '资源池',
            dataIndex: "dataCenterId",
            valueType: 'select',
            search: true,
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await dataCenterSelectList({});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.dataCenterId,
                    })) || []
                );
            },
        },
        {
            title: '规格',
            dataIndex: "skuId",
            valueType: 'select',
            search: true,
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await skuSelectList({});
                return (
                    result.data?.map((item) => ({
                        label: item.skuName,
                        value: item.skuId,
                    })) || []
                );
            },
        },
        {
            title: '所属资源池',
            dataIndex: ['dataCenter', "dataCenterName"],
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '所属组织',
            dataIndex: "organizationId",
            valueType: 'select',
            search: access.isSystem,
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await organizationSelectList({includeSystem:true});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.organizationId,
                    })) || []
                );
            },
        },
        {
            title: '主机ID',
            dataIndex: 'hostComputerId',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },

        {
            title: '主机名称',
            dataIndex: 'name',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '状态',
            dataIndex: 'status',
            search: true,
            valueType: 'select',
            valueEnum: HostComputerOrderStatusEnum,
            // tip: '黄色为告警信息，红色为异常信息',
            render: (value, record, index) => {
                if (record.orderId != "") {
                    return <Space><Badge count={"已出售"} showZero color="#faad14"/></Space>;
                } else {
                    return <Space><Badge count={"空闲"} showZero color="#00CC66"/></Space>;
                }
            },
        },
        {
            title: '租户',
            dataIndex: 'organizationName',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '规格',
            dataIndex: ['sku', "skuName"],
            search: false,
            valueType: 'text',
            ellipsis: true, // 关闭自动换行
        },

        {
            title: '机房编号',
            dataIndex: 'machineRoomNo',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '机柜编号',
            dataIndex: 'cabinetNo',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: 'U位区间',
            dataIndex: 'uPosition',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '设备类型',
            dataIndex: 'deviceType',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '主机IP',
            dataIndex: 'hostIp',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: 'IP地址',
            dataIndex: 'ip',
            search: true,
            hidden: true,
        },
        {
            title: '网络类型',
            dataIndex: 'networkConnType',
            valueType: 'select',
            valueEnum: NetworkConnTypeEnum,
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '互联网IP',
            dataIndex: 'publicIpList',
            search: false,
            ellipsis: true, // 关闭自动换行
            render: (value, record, index) => {
                let result = [];
                for (let i = 0; i < record.publicIpList?.length; i++) {
                    result.push(
                        <div key={i}>
                            <b>{record.publicIpList[i]}</b>
                            {i < record.publicIpList.length - 1 && <br/>}
                        </div>
                    );
                }
                return <div>{result}</div>;
            },
        },
        {
            title: '系统',
            dataIndex: 'systemOS',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            ellipsis: true, // 关闭自动换行
            render: (_, record) => {
                return [
                    <Link to={`/power/host-computer/edit/` + record.hostComputerId}>
                        编辑
                    </Link>,
                    record.orderId != '' && <a
                        key="configNetwork"
                        onClick={() => {
                            setCurrentRow(record);
                            handleConfigNetworkModelVisible(true);
                        }}
                    >
                        配置网络
                    </a>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<HostComputerListItem, API.ListPagination>
                headerTitle="主机列表"
                actionRef={actionRef}
                rowKey="hostComputerId"
                search={{
                    labelWidth: 90,
                    span: 7
                }}

                scroll={{x: true}}
                toolBarRender={() => [
                    <Link to={"/power/host-computer/add"}>
                        <Button
                            type="primary"
                            key="primary"
                        >
                            <PlusOutlined/> 新建
                        </Button>
                    </Link>
                ]}
                options={{
                    density: true,
                    fullScreen: true,
                    reload: true,
                    setting: false
                }}
                request={hostComputerList}
                columns={columns}
                rowSelection={rowSelection}
                expandable={{
                    expandedRowRender: (record) =>
                        <div>
                            <p style={{marginLeft: 80}}>主机功耗：{record.powerConsumption}W</p>
                            <p style={{marginLeft: 80}}>管理账号：{record.loginName}&nbsp; &nbsp; &nbsp;管理密码：{record.loginPassword}</p>
                            <p style={{marginLeft: 80}}>IPMI
                                IP：{record.ipmiIp}&nbsp; &nbsp; &nbsp;IPMI账号：{record.ipmiIpLoginName}&nbsp; &nbsp; &nbsp;IPMI密码：{record.ipmiIpLoginPassword}</p>
                            <p style={{marginLeft: 80}}>IPoIB IP：{record.ipoibIp}</p>
                        </div>,
                    rowExpandable: (record) => true,
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '删除主机',
                                // icon: <ExclamationCircleFilled />,
                                content: '删除主机前，请确认主机关联订单、资源已清除，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}

            <ConfigNetworkModalForm
                modalVisible={configNetworkModelVisible}
                currentHostComputerRow={currentRow}
                onClose={() => {
                    handleConfigNetworkModelVisible(false);
                }}
                onSuccess={() => {
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }}
            />
        </PageContainer>
    );
};

export default HostComputerList;
